<?php

/**
 * Script used to return a file connected to a spesific project from the
 * database
 */
// Connect to the database
require_once '../../../db.php';

if (!isset($_GET['id']))  // No id given ?
    die("Fant ikke filen"); // Give an error message


$sql = 'SELECT * FROM projectdocuments WHERE projectid=?';
$sth = $db->prepare($sql);
$sth->execute(array($_GET['id']));
$row1 = $sth->fetch();

if ($row1) {
// Get the mime type, content, size and file name from the database
    $sql = 'SELECT mime, content, size, name FROM documents WHERE id=?';
    $sth = $db->prepare($sql);
    $sth->execute(array($row1[1])); // Get information about the given file
    $row = $sth->fetch();
    if ($row) {                     // If we found the file
        header('Content-type: ' . $row['mime']);  // Set the correct mime type
        header('Content-length: ' . $row['size']); // Set the content length
        // If we follow a link to get this file, get the save as dialog
        header("Content-Disposition: attachment; filename=\"{$row['name']}\"");
        echo $row['content'];      // Send the content of the file
    } else        // No file found
        echo ("No attachment found");  // Send an "error message"
} else {
    echo ("The project doesn't have an attachment");
}
?>